#import "ImageAddingView.h"
#import "UIActionSheet+BlocksKit.h"
#import "UIImageView+AFNetworking.h"
#import "CTAssetsPickerController.h"
#import "MWPhotoBrowser.h"
#import "UIAlertView+BlocksKit.h"

static const NSInteger maximumNumberOfImages = 4;
static NSString *const imagesIdentifier = @"imageCell";

@interface ImageAddingView () <UICollectionViewDelegate, UICollectionViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate, CTAssetsPickerControllerDelegate, MWPhotoBrowserDelegate>

@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) IBOutlet UIButton *addButton;
@property (nonatomic, strong)ALAssetsLibrary *assetsLibrary;
@property (nonatomic, strong)NSArray *loadedImageDatas;
@property (nonatomic, strong)NSArray *selectedImageAssets;
@property (nonatomic, strong)NSArray *PhotoBrowserDataSource;

@end

@implementation ImageAddingView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setup];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self) {
        [self setup];
    }
    return self;
}

- (void)setIfHiddenAddBtn:(BOOL)ifHiddenAddBtn {
    _ifHiddenAddBtn = ifHiddenAddBtn;
    self.addButton.hidden = _ifHiddenAddBtn;
}

- (void)setup
{
    [[NSBundle mainBundle] loadNibNamed:@"ImageAddingView" owner:self options:nil];
    _collectionView.frame = self.bounds;
    _collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self addSubview:_collectionView];
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:imagesIdentifier];
    [_collectionView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionOld context:NULL];
    _assetsLibrary = [[ALAssetsLibrary alloc] init];
    _imageDatas = @[];
    _selectedImageAssets = @[];
}

- (void)dealloc
{
    [_collectionView removeObserver:self forKeyPath:@"contentSize" context:NULL];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == _collectionView) {
        CGFloat heightDelta = _collectionView.contentSize.height - _collectionView.frame.size.height;
        CGRect frame = _collectionView.frame;
        frame.size = _collectionView.contentSize;
        _collectionView.frame = frame;
        self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, _collectionView.contentSize.width, _collectionView.contentSize.height);
        if(_imageFrameBlock) {
            _imageFrameBlock(heightDelta);
        }
        
    }
}

- (void)setBackColor:(UIColor *)backColor
{
    _collectionView.backgroundColor = backColor;
}

#pragma mark - Loading images

- (void)setImageDatas:(NSArray *)imageDatas
{
    _imageDatas = imageDatas;
    _loadedImageDatas = imageDatas;
    [_collectionView reloadData];
}

#pragma mark - Picking images

- (IBAction)addImage:(id)sender
{
    UIActionSheet *addImageFrom = [UIActionSheet bk_actionSheetWithTitle:NSLocalizedString(@"添加图片", nil)];
    [addImageFrom bk_addButtonWithTitle:NSLocalizedString(@"拍照", nil) handler:^{
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            picker.delegate = self;
//            picker.allowsEditing = YES;
            if (_imagePickerBlock) {
                _imagePickerBlock(picker);
            }
        }
    }];
    [addImageFrom bk_addButtonWithTitle:NSLocalizedString(@"从手机相册选择", nil) handler:^{
        CTAssetsPickerController *picker = [[CTAssetsPickerController alloc] init];
        picker.title = NSLocalizedString(@"选取图片", nil);
        picker.assetsFilter = [ALAssetsFilter allPhotos];
        picker.assetsLibrary = _assetsLibrary;
        picker.selectedAssets = [NSMutableArray arrayWithArray:_selectedImageAssets];
        picker.delegate = self;
        if (_imagePickerBlock) {
            _imagePickerBlock(picker);
        }
    }];
    [addImageFrom bk_setCancelButtonWithTitle:NSLocalizedString(@"取消", nil) handler:nil];
    [addImageFrom showInView:self.window];
}

#pragma mark - UIImagePickerControllerDelegate

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        [ESHUDView showLoading];
    }];
    if ([[info objectForKey:UIImagePickerControllerMediaType] isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [_assetsLibrary writeImageToSavedPhotosAlbum:image.CGImage metadata:[info objectForKey:UIImagePickerControllerMediaMetadata] completionBlock:^(NSURL *assetURL, NSError *error) {
            [_assetsLibrary assetForURL:assetURL resultBlock:^(ALAsset *asset) {
                NSMutableArray *tempArray = [NSMutableArray arrayWithArray:_selectedImageAssets];
                [tempArray addObject:asset];
                _selectedImageAssets = tempArray;
                tempArray = [NSMutableArray arrayWithArray:_imageDatas];
                [tempArray addObject:[UIImage imageWithData:UIImageJPEGRepresentation(image, 0.4)]];
                _imageDatas = tempArray;
                [_collectionView reloadData];
                [ESHUDView dismiss];
            } failureBlock:^(NSError *error) {
                [[ESHUDView sharedInstance] showErrorMessage:NSLocalizedString(@"出错了", nil) dismissBlock:nil];
            }];
        }];
    }
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - CTAssetsPickerControllerDelegate

- (void)assetsPickerController:(CTAssetsPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    [picker.presentingViewController dismissViewControllerAnimated:YES completion:nil];
    _selectedImageAssets = assets;
    NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:[assets count]];
    for (ALAsset *asset in assets) {
        CGImageRef iref = asset.defaultRepresentation.fullResolutionImage;
        if (iref) {
            UIImage *image = [UIImage imageWithCGImage:iref];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.4);
            image = [UIImage imageWithData:imageData];
            [tempArray addObject:image];
        }
    }
    if (_loadedImageDatas) {
        [tempArray insertObjects:_loadedImageDatas atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [_loadedImageDatas count])]];
    }
    _imageDatas = tempArray;
    [_collectionView reloadData];
}

- (BOOL)assetsPickerController:(CTAssetsPickerController *)picker shouldSelectAsset:(ALAsset *)asset
{
    if (picker.selectedAssets.count >= maximumNumberOfImages) {
        [[ESHUDView sharedInstance] showErrorMessage:[NSString stringWithFormat:NSLocalizedString(@"最多只能选择%d张照片", nil), maximumNumberOfImages] dismissBlock:nil];
        return NO;
    }
    if (!asset.defaultRepresentation) {
        UIAlertView *alertView =
        [[UIAlertView alloc] initWithTitle:nil
                                   message:NSLocalizedString(@"该图片还未下载到设备", nil)
                                  delegate:nil
                         cancelButtonTitle:nil
                         otherButtonTitles:NSLocalizedString(@"好", nil), nil];
        [alertView show];
    }
    return (asset.defaultRepresentation != nil);
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return ([_imageDatas count] >= maximumNumberOfImages) ? maximumNumberOfImages : ([_imageDatas count] + 1);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:imagesIdentifier forIndexPath:indexPath];
    [[cell viewWithTag:4444] removeFromSuperview];
    if (([_imageDatas count] < maximumNumberOfImages) &&
        (indexPath.row == [_imageDatas count])) {
        _addButton.tag = 4444;
        [cell addSubview:_addButton];
    } else {
        UIImageView *image = [[UIImageView alloc] initWithImage:_imageDatas[indexPath.row]];
        image.contentMode = UIViewContentModeScaleAspectFill;
        image.clipsToBounds = YES;
        image.frame = cell.bounds;
        image.tag = 4444;
        [cell addSubview:image];
    }
    return cell;
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *imageViews = [NSMutableArray arrayWithCapacity:[_imageDatas count]];
    for (UIImage *image in _imageDatas) {
        MWPhoto *photo = [MWPhoto photoWithImage:image];
        [imageViews addObject:photo];
    }
    _PhotoBrowserDataSource = imageViews;
    
    MWPhotoBrowser *imageBrowser = [[MWPhotoBrowser alloc] initWithDelegate:self];
    imageBrowser.displayActionButton = !_ifHiddenAddBtn;
    imageBrowser.alwaysShowControls = NO;
    imageBrowser.enableGrid = NO;
    imageBrowser.startOnGrid = NO;
    [imageBrowser setCurrentPhotoIndex:indexPath.row];
    [[UIUtil viewControllerHasNavgation:self].navigationController pushViewController:imageBrowser animated:YES];
}

#pragma mark - MWPhotoBrowserDelegate

- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser
{
    return [_PhotoBrowserDataSource count];
}

- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index
{
    if (index < [_PhotoBrowserDataSource count]) {
        return _PhotoBrowserDataSource[index];
    }
    return nil;
}

- (void)photoBrowser:(MWPhotoBrowser *)photoBrowser actionButtonPressedForPhotoAtIndex:(NSUInteger)index
{
    [UIAlertView bk_showAlertViewWithTitle:nil message:NSLocalizedString(@"删除这张照片吗？", nil) cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:@[NSLocalizedString(@"删除", nil)] handler:^(UIAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex) {
            NSMutableArray *temp = [NSMutableArray arrayWithArray:_PhotoBrowserDataSource];
            [temp removeObjectAtIndex:index];
            _PhotoBrowserDataSource = temp;
            [photoBrowser reloadData];
            temp = [NSMutableArray arrayWithArray:_imageDatas];
            [temp removeObjectAtIndex:index];
            _imageDatas = temp;
            [_collectionView reloadData];
            if (![_PhotoBrowserDataSource count]) {
                [photoBrowser.navigationController popViewControllerAnimated:YES];
            }
        }
    }];
}

@end
